package cn.liutao.common.servlet;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import cn.liutao.common.exception.BadRequestException;
import cn.liutao.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author liutao
 * @Description 异常处理
 * @date 2023/10/31 14:47
 * @Version 1.0
 */
@WebServlet("/error")
@Slf4j
public class ErrorServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Exception exception = (Exception) req.getAttribute("javax.servlet.error.exception");
        Integer statusCode = (Integer) req.getAttribute("javax.servlet.error.status_code");
        String servletName = (String) req.getAttribute("javax.servlet.error.servlet_name");
        String message="系统异常";
        if (ObjectUtil.isNotNull(exception)) {
            message = exception.getMessage();
        }else if (resp.getStatus()== HttpStatus.HTTP_NOT_FOUND){
            message = "访问的资源不存在";
        }
        if (exception instanceof BadRequestException){
            statusCode = ((BadRequestException) exception).getStatus();
        }
        log.error("【统一异常处理】：servlet:{}:code:{}:msg:{}", statusCode, servletName, message, exception);
        ServletUtils.error(resp, message, statusCode);
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
